<!--
	作者：lsd
	时间：2020-4-15
	描述：采购申请清单
-->
<template>
  <div class="m-view-purchaserApplayList m-window">
    <!-- 搜索头 -->
    <div class="m-condition">
      <el-form
        :model="formSearch"
        ref="formSearch"
        label-width="90px"
        :inline-message="true"
        label-position="left"
      >
        <el-row :gutter="10">
          <el-col :span="5">
            <el-form-item label="工厂" class="rightItem">
              <el-select
                v-model="formSearch.plantCode"
                filterable
                :filter-method="filterFactory"
                placeholder="请选择工厂"
              >
                <el-option
                  v-for="item in optionsFactory"
                  :key="item.plantCode"
                  :label="item.plantName"
                  :value="item.plantCode"
                >
                  <span style="float: left">{{ item.plantName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.plantCode
                  }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="申请日期" class="rightItem">
              <el-date-picker
                v-model="formSearch.sapCreateDate"
                placeholder="开始日期"
                value-format="yyyy-MM-dd"
                clearable
                :picker-options="timeRange(formSearch.sapCreateDateEnd, true)"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-date-picker
              v-model="formSearch.sapCreateDateEnd"
              clearable
              placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="timeRange(formSearch.sapCreateDate)"
            >
            </el-date-picker>
          </el-col>
          <el-col :span="5">
            <el-form-item label="采购申请号" class="rightItem">
              <el-input
                v-model.trim="formSearch.requestNo"
                placeholder="请输入"
                clearable
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="状态" class="rightItem">
              <el-select
                v-model="formSearch.auditFlag"
                placeholder="请选择状态"
                @change="search"
              >
                <el-option
                  v-for="item in [
                    { name: '未发布', value: 0 },
                    { name: '已发布', value: 2 },
                  ]"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="5">
            <el-form-item label="采购组" class="rightItem">
              <el-input
                v-model.trim="formSearch.purGroup"
                placeholder="请输入"
                clearable
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="批准日期" class="rightItem">
              <el-date-picker
                v-model="formSearch.auditDate"
                placeholder="开始日期"
                value-format="yyyy-MM-dd"
                clearable
                :picker-options="timeRange(formSearch.auditDateEnd, true)"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-date-picker
              v-model="formSearch.auditDateEnd"
              clearable
              placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="timeRange(formSearch.auditDate)"
            >
            </el-date-picker>
          </el-col>
          <el-col :span="2" :offset="2">
            <el-button type="primary" @click="search(true)">查询</el-button>
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="synchronization"
              >同步采购申请</el-button
            >
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="puechacserOrder"
              >同步采购订单</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 表单 -->
    <div class="m-agTable m-bottom m-top2" v-loading="loading">
      <ag-grid-component
        ref="agGridComponent"
        :tableName="'puechaserApplyList'"
        :getGridOptions="gridOptions"
        :getColumnDefs="columnDefs"
        :getRowSelection="'multiple'"
        :isColFit="true"
        :systemInfo="$systemInfo"
      ></ag-grid-component>
    </div>

    <!-- 页脚 -->
    <div class="m-page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.currentPage"
        :page-sizes="[30, 50, 100, 150, 200]"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import gridOptions from "lesso-common/public/gridOptions";

/**
 * @group puechaserApplyList
 * 采购员管理
 */
export default {
  name: "puechaserApplyList",
  data() {
    return {
      formSearch: {
        plantCode: "",
        requestNo: "",
        sapCreateDate: "",
        sapCreateDateEnd: "",
        auditFlag: 2,
        purGroup: "",
        auditDate: "",
        auditDateEnd: "",
      },
      rowData: [], // 表格数据
      //下拉列表
      optionsFactory: [], //工厂下拉框列表
      optionsTempFactory: [], //工具人，专门用来过滤的
      //表格参数
      gridOptions: "",
      columnDefs: [],
      //页脚参数
      pageInfo: {
        pageSize: 100,
        currentPage: 1,
      },
      total: 0,
      //加载参数
      loading: false, //页面的
      diaView: false,
    };
  },
  beforeMount() {
    this.gridOptions = Object.assign(
      {
        context: {
          componentParent: this,
        },
        enableColResize: true,
        //rowSelection: "multiple",
        suppressRowClickSelection: true, //单元格选中,false为选中整行
        localeText: localeText,
        enableCellChangeFlash: true,
        enableRangeSelection: true,
        enableFilter: true, //列过滤器
        enableSorting: true, //列排序
        animateRows: true, //排序动画
      },
      gridOptions({
        dragSelectCheckbox: true,
        singleSelection: true,
        operation: true,
      })
    );
    this.columnDefs = [
      {
        headerName: "采购申请",
        field: "requestNo",
        width: 130,
        checkboxSelection: true,
        headerCheckboxSelection: true,
      },
      { headerName: "项目", field: "requestMxno", width: 120 },
      { headerName: "申请日期", field: "sapCreateDate", width: 150 },
      { headerName: "批准日期", field: "auditDate", width: 150 },
      { headerName: "物料组", field: "matgroup", width: 150 },
      { headerName: "物料组描述", field: "matgroupName", width: 150 },
      { headerName: "物料编码", field: "matCode", width: 150 },
      { headerName: "物料描述", field: "matName", width: 250 },
      { headerName: "申请数量", field: "requestAmount", width: 150 },
      { headerName: "单位", field: "unitCode", width: 120 },
      { headerName: "备注", field: "remark", width: 150 },
      { headerName: "工厂", field: "plantName", width: 250 },
      { headerName: "申请部门", field: "purGroupName", width: 150 },
      { headerName: "申请者", field: "requester", width: 120 },
      {
        headerName: "状态",
        field: "auditFlag",
        width: 200,
        cellRenderer: (params) => {
          let tip = "审批通过";
          return tip;
        },
      },
    ];
  },
  mounted() {
    this.search();
    this.getFactoryList(true);
  },
  methods: {
    /**
     * @vuese
     * 查询方法
     *
     * @arg 参数是布尔值， true就是点击触发，false就是非点击触发
     */
    search(isClick) {
      this.loading = true;
      this.pageInfo.currentPage = isClick ? 1 : this.pageInfo.currentPage;
      let param = {
        sapNum: this.$global.user.idmNum,
        ...this.formSearch,
        ...this.pageInfo,
      };

      //参数兜底
      if (param.sapCreateDate && !param.sapCreateDateEnd) {
        param.sapCreateDateEnd = this.getNowTime();
      }
      if (!param.sapCreateDate && param.sapCreateDateEnd) {
        param.sapCreateDate = "1970-01-01";
      }
      if (!param.auditDate && param.auditDateEnd) {
        param.auditDate = "1970-01-01";
      }
      if (param.auditDate && !param.auditDateEnd) {
        param.auditDateEnd = this.getNowTime();
      }

      _Api
        .searchPuechaserApplyList(param)
        .then((res) => {
          this.loading = false;
          if (res.data.code == 1) {
            this.rowData = res.data.rows;
            this.total = res.data.total;
            this.$refs.agGridComponent.gridOptions.api.setRowData(this.rowData);
          } else {
            this.$alert(res.data.info, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure",
            });
          }
        })
        .catch((err) => {
          this.loading = false;
          this.$alert(err.data.info, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        });
    },

    /**
     * @vuese
     * 同步采购方法
     */
    synchronization() {
      let plantCode = this.formSearch.plantCode;
      if (plantCode == "" || plantCode == null) {
        this.$alert("请选择工厂", {
          showClose: false,
          confirmButton: "确定",
          customClass: "alertFailure",
        });
        return;
      }
      let {
        sapCreateDate,
        sapCreateDateEnd,
        auditDate,
        auditDateEnd,
      } = this.formSearch;
      let param = {
        sapCreateDate,
        sapCreateDateEnd,
        auditDate,
        auditDateEnd,
        plantCode,
        creator: this.$global.user.employeeName,
        creatorId: this.$global.user.id,
        sapNum: this.$global.user.idmNum,
      };

      //参数兜底
      if (param.sapCreateDate && !param.sapCreateDateEnd) {
        param.sapCreateDateEnd = this.getNowTime();
      }
      if (!param.sapCreateDate && param.sapCreateDateEnd) {
        param.sapCreateDate = "1970-01-01";
      }
      if (!param.auditDate && param.auditDateEnd) {
        param.auditDate = "1970-01-01";
      }
      if (param.auditDate && !param.auditDateEnd) {
        param.auditDateEnd = this.getNowTime();
      }

      this.loading = true;
      _Api
        .syncPuechaserApplyList(param)
        .then((res) => {
          this.loading = false;
          if (res.data.code == 1) {
            // this.rowData = res.data.rows;
            // this.total = res.data.total
            // this.$refs.agGridComponent.gridOptions.api.setRowData(this.rowData);
            this.$message({ message: "同步成功", type: "success" });
            this.search();
          } else {
            this.$alert(res.data.info, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure",
            });
          }
        })
        .catch((err) => {
          this.loading = false;
          this.$alert(err.data.info, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        });
    },
    // 同步采购订单
    puechacserOrder() {
      let plantCode = this.formSearch.plantCode;
      if (plantCode == "" || plantCode == null) {
        this.$alert("请选择工厂", {
          showClose: false,
          confirmButton: "确定",
          customClass: "alertFailure",
        });
        return;
      }
      console.log(this.formSearch, "formSearch");
      if (
        this.formSearch.sapCreateDate == "" ||
        (this.formSearch.sapCreateDate == null &&
          this.formSearch.sapCreateDateEnd == null) ||
        this.formSearch.sapCreateDateEnd == ""
      ) {
        this.$alert("请选择申请日期", {
          showClose: false,
          confirmButton: "确定",
          customClass: "alertFailure",
        });
        return;
      }
      let {
        sapCreateDate,
        sapCreateDateEnd,
        auditDate,
        auditDateEnd,
      } = this.formSearch;
      let param = {
        sapCreateDate,
        sapCreateDateEnd,
        auditDate,
        auditDateEnd,
        plantCode,
        creator: this.$global.user.employeeName,
        creatorId: this.$global.user.id,
        sapNum: this.$global.user.idmNum,
      };

      //参数兜底
      if (param.sapCreateDate && !param.sapCreateDateEnd) {
        param.sapCreateDateEnd = this.getNowTime();
      }
      if (!param.sapCreateDate && param.sapCreateDateEnd) {
        param.sapCreateDate = "1970-01-01";
      }
      if (!param.auditDate && param.auditDateEnd) {
        param.auditDate = "1970-01-01";
      }
      if (param.auditDate && !param.auditDateEnd) {
        param.auditDateEnd = this.getNowTime();
      }

      this.loading = true;
      _Api
        .syncPuechaserApplyList(param)
        .then((res) => {
          let requstParam = {
            plantCode: this.formSearch.plantCode,
            startDate: this.formSearch.sapCreateDate,
            endDate: this.formSearch.sapCreateDateEnd,
          };

          _Api
            .puechaserApplyOrder(requstParam)
            .then((res) => {
              this.loading = false;
          
              if (res.data.code == 1) {
                this.$message({ message: res.data.info, type: "success" });
                this.search();
              } else {
                this.$alert(res.data.info, {
                  showClose: false,
                  confirmButton: "确定",
                  customClass: "alertFailure",
                });
              }
            })
            .catch((err) => {
              this.loading = false;
              this.$alert(err.data.info, {
                showClose: false,
                confirmButton: "确定",
                customClass: "alertFailure",
              });
            });
        })
        .catch((err) => {
          this.loading = false;
          this.$alert(err.data.info, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        });
    },

    /**
     * @vuese
     * 根据账号获取工厂列表方法
     */
    getFactoryList() {
      this.loadingDia = true;
      _Api
        .getFactoryListBySapNum({ sapNum: this.$global.user.idmNum })
        .then((res) => {
          this.loadingDia = false;
          if (res.data.code == 1) {
            this.optionsFactory = res.data.rows;
            this.optionsTempFactory = res.data.rows;
          } else {
            this.$alert(res.data.info, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure",
            });
          }
        })
        .catch((err) => {
          this.loadingDia = false;
          this.$alert(err.data.info, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        });
    },

    /**
     * @vuese
     * 改变页脚总条数方法
     *
     * @arg 参数是 int 值，代表一页有多少条数据
     */
    handleSizeChange(val) {
      this.pageInfo.pageSize = val;
      this.pageInfo.currentPage = 1;
      this.search();
    },

    /**
     * @vuese
     * 翻页方法
     *
     * @arg 参数是 int 值，代表页数
     */
    handleCurrentChange(val) {
      this.pageInfo.currentPage = val;
      this.search();
    },

    /**
     * @vuese
     * 日期可选范围
     *
     * @arg startTime参数是时间， 代表为最小时间； flag是布尔值， true为开始时间范围， false为结束时间范围
     */
    timeRange(startTime, flag) {
      return {
        disabledDate(time) {
          let tempTime = new Date(startTime).getTime() || 0;
          let minTime = time.getTime() + 24 * 60 * 60 * 1000;

          if (tempTime == 0) {
            return time.getTime() > Date.now();
          } else if (flag) {
            return time.getTime() > tempTime;
          } else {
            return minTime < tempTime || time.getTime() > Date.now();
          }
        },
      };
    },

    /**
     * @vuese
     * 获取当天的时间 格式：yyyy-mm-dd
     */
    getNowTime() {
      let myDate = new Date();
      let month = myDate.getMonth() + 1;
      let day = myDate.getDate();
      let nowTime = `${myDate.getFullYear()}-${
        month < 10 ? "0" + month : month
      }-${day < 10 ? "0" + day : day}`;
      return nowTime;
    },

    /**
     * @vuese
     * 过滤工厂
     *
     * @arg value:传入的是检索值, 用于过滤
     */
    filterFactory(value) {
      if (value != "") {
        this.optionsFactory = this.optionsTempFactory.filter(
          (item) =>
            item.plantCode.indexOf(value) > -1 ||
            item.plantName.indexOf(value) > -1
        );
      } else {
        this.optionsFactory = this.optionsTempFactory;
      }
    },
  },
};
</script>

<style lang="less">
.m-view-purchaserApplayList {
  .el-form {
    .el-form-item {
      margin-bottom: 0;
    }
  }
}
</style>